<template>
  <div>
    <el-page-header @back="goBack" style="height: 50px;font-size: 30px;line-height: 50px;border-bottom: 1px solid rgb(237, 239, 241)" :content="this.course.title"></el-page-header>
    <div style="height: 100%">
      <div class="el-col-6" style="height: 1020px;padding: 10px;border-right: 1px solid #edeff1">
        <div class="menu_top_div">
          <div class="el-col-20" style="text-align: left;padding-left: 10px">
            章节管理
          </div>
          <div class="el-col-4 addChapterBtn" @click="addChapter">
            <i class="el-icon-plus" style="font-size: 20px"></i>
          </div>
        </div>
        <div>
          <el-tree
            :data="data"
            :expand-on-click-node="true"
            @node-drag-end="handleDragEnd"
            @node-click="handleNodeClick">
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <div class="el-col-20 tree_left">
                <span>{{data.sort}}  {{ data.name }}</span>
              </div>
              <div class="el-col-4 tree_right">
                <el-button
                  v-if="data.level == 1"
                  type="text"
                  size="small"
                  @click="() => addSection(data)"
                  @click.stop
                >
                  <i class="el-icon-plus" style="font-size: 20px"></i>
                </el-button>
              </div>
            </div>
          </el-tree>
        </div>
      </div>
      <div class="el-col-18" style="height: 100%;padding: 50px 50px">
        <div v-if="showChapterManage">
          <div class="optionDiv">
            <span class="showText">{{showText}}</span>
            <div class="optionButton">
                <el-button type="danger" v-if="!rightType" @click="deleteChapter">删除</el-button>
              <el-popover
                placement="top"
                width="160"
                v-model="visible">
                <p>确认取消吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                  <el-button type="primary" size="mini" @click="cancleFun">确定</el-button>
                </div>
                <el-button type="danger" slot="reference" v-if="rightType">取消</el-button>
              </el-popover>
              <el-button type="success" @click="saveChapter">保存</el-button>
            </div>
          </div>
          <el-divider></el-divider>
          <el-form :model="chapterData"
                   label-position="left"
                   label-width="80px"
                   :rules="chapter_info_rules"
                   ref="chapter_info_form"
          >
            <el-form-item label="章名称" prop="name">
              <el-input v-model="chapterData.name"
                        maxlength="20"
                        show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="章简介">
              <el-input type="textarea"
                        rows="3"
                        maxlength="200"
                        show-word-limit
                        v-model="chapterData.introduction">
              </el-input>
            </el-form-item>
          </el-form>
          <el-divider></el-divider>
        </div>
        <div v-if="showSectionManage" class="selectManageDiv">
          <div class="optionDiv">
            <span class="showText">{{showText}}</span>
            <div class="optionButton">
              <el-button type="danger" v-if="!rightType" @click="deleteSection">删除</el-button>
              <el-popover
                placement="top"
                width="160"
                v-model="visible">
                <p>确认取消吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                  <el-button type="primary" size="mini" @click="cancleFun">确定</el-button>
                </div>
                <el-button type="danger" slot="reference" v-if="rightType">取消</el-button>
              </el-popover>
              <el-button type="success" @click="saveSection">保存</el-button>
            </div>
          </div>
          <el-divider></el-divider>
          <el-form :model="sectionData"
                   label-position="left"
                   label-width="80px"
                   :rules="section_info_rules"
                   ref="section_info_form"
          >
            <el-form-item label="节名称" prop="name">
              <el-input v-model="sectionData.name"
                        maxlength="20"
                        show-word-limit>
              </el-input>
            </el-form-item>
            <el-form-item label="节视频" prop="videoUrl">
              <el-upload
                class="upload_div"
                :auto-upload="true"
                action=""
                :show-file-list="false"
                :http-request="fileUpload"
                :before-upload="beforeVideoUpload"
                :multiple="false">
                <el-button size="small" type="primary">
                  <span v-if="!showVideo" >点击上传</span>
                  <span v-else>点击修改</span>
                </el-button>
              </el-upload>
              <div style="">
                <el-progress v-if="showProgress" type="circle" :percentage="progress"></el-progress>
                <video v-if="showVideo" :src="sectionData.videoUrl" controls="controls"
                       style="height: 300px;width: 500px"></video>
              </div>
              <el-input v-model="sectionData.videoUrl"
                        type="hidden" style="display: none">
              </el-input>
            </el-form-item>
            <el-form-item label="节资料">
              <el-upload
                class="upload_div"
                :auto-upload="true"
                action=""
                :http-request="fileUploadCom"
                :show-file-list="false"
                :multiple="false">
                <el-button size="small" type="primary">
                  <span v-if="!showFile">点击上传</span>
                  <span v-else>点击修改</span>
                </el-button>
              </el-upload>
              <el-progress v-if="fileIng" :percentage="fileProgress"></el-progress>
              <a v-if="showFile" :href="sectionData.file">
                <div style="height: 20px;">
                  <i class="el-icon-document" style="font-size: 20px"></i>
                  <span style="font-size: 20px">{{sectionData.fileName}}</span>
                </div>
              </a>
              <el-input v-model="sectionData.file" style="display: none"></el-input>
            </el-form-item>
          </el-form>
          <el-divider></el-divider>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CourseManageMain',
  data () {
    return {
      // JSON.parse(JSON.stringify(data))
      data: [],
      courseId: this.$route.query.courseId,
      course: '',
      chapterData: {
      },
      showText: '',
      // rightType为true表示添加；为false表示修改
      rightType: true,
      // 取消框的显示隐藏
      visible: false,
      sectionData: {
        sectionId: '',
        chapterId: '',
        name: '',
        fileName: '',
        file: '',
        sort: '',
        videoUrl: '',
        date: '',
        level: '',
        remove: ''
      },
      selectChapter: '',
      showChapterManage: false,
      showSectionManage: false,
      videoList: [],
      file_list: [],
      showUpload: true,
      showVideo: false,
      showFile: false,
      showProgress: false,
      hideUpload: false,
      limitCount: 1,
      progress: 0,
      fileIng: false,
      fileProgress: 0,
      chapter_info_rules: {
        name: [
          {required: true, message: '请输入章名称', trigger: 'blur'}
        ]
      },
      section_info_rules: {
        name: [
          {required: true, message: '请输入节名称', trigger: 'blur'}
        ],
        videoUrl: [
          {required: true, message: '请上传视频', trigger: 'blur'}
        ]
      }
    }
  },
  mounted () {
    this.getCourseCS()
    this.getCourseById()
  },
  methods: {
    addSection (data) {
      var lastSort = 1
      // eslint-disable-next-line eqeqeq
      if (data.children.length != 0) {
        lastSort = parseInt(data.children[data.children.length - 1].sort) + 1
      }
      // eslint-disable-next-line no-undef
      const newSection = {
        sectionId: '',
        chapterId: data.chapterId,
        name: '',
        fileName: '',
        file: '',
        sort: lastSort,
        videoUrl: '',
        level: '2',
        remove: '1'
      }
      this.rightType = true
      this.showText = '添加节'
      this.selectChapter = data
      this.setRightSection(newSection)
      this.showVideo = false
      this.showFile = false
      this.showChapterManage = false
      this.showSectionManage = true
    },
    handleDragEnd (draggingNode, dropNode, dropType, ev) {
    },
    handleNodeClick (data, node) {
      this.showVideo = false
      this.showFile = false
      this.rightType = false
      // eslint-disable-next-line eqeqeq
      if (data.level == 1) {
        this.setRightChapter(data)
        this.rightType = false
        this.showText = '编辑章'
        this.showChapterManage = true
        this.showSectionManage = false
        // eslint-disable-next-line eqeqeq
      } else if (data.level == 2) {
        this.setRightSection(data)
        this.rightType = false
        this.showText = '编辑节'
        this.selectChapter = node.parent.data
        // eslint-disable-next-line eqeqeq
        if (data.videoUrl != null && data.videoUrl != '') {
          this.showVideo = true
        }
        // eslint-disable-next-line eqeqeq
        if (data.file != null && data.file != '') {
          this.showFile = true
        }
        this.showSectionManage = true
        this.showChapterManage = false
      }
    },
    addChapter () {
      var lastSort = 1
      // eslint-disable-next-line eqeqeq
      if (this.data.length != 0) {
        lastSort = parseInt(this.data[this.data.length - 1].sort) + 1
      }
      const newChapter = {
        chapterId: '',
        courseId: this.courseId,
        name: '',
        introduction: '',
        level: '1',
        sort: lastSort,
        remove: 1,
        children: []
      }
      // 显示右侧编辑
      this.showChapterManage = true
      this.showText = '添加章'
      this.rightType = true
      this.setRightChapter(newChapter)
    },
    // 上传节视频
    async fileUpload (file) {
      this.showProgress = true
      this.showVideo = false
      var _this = this
      var host = this.$store.state.ossData.host
      var response = this.$Utils.getSignature('video')
      var requestData = new FormData()
      await response.then(res => {
        requestData = this.$Utils.fileUpload(file.file, res)
      })
      await this.$axios.post(host, requestData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: progressEvent => {
          let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
          // file.onProgress({percent: complete})
          _this.progress = complete
        }
      })
        .then(function (response) {
          // eslint-disable-next-line eqeqeq
          if (response.status == 200) {
            _this.sectionData.videoUrl = host + '/' + requestData.get('key')
            _this.showProgress = false
            _this.showVideo = true
          }
        })
    },
    // 上传视频判断时长
    beforeVideoUpload (file) {
      var _this = this
      var url = URL.createObjectURL(file)
      var audioElement = new Audio(url)
      var duration
      audioElement.addEventListener('loadedmetadata', function (_event) {
        duration = audioElement.duration // 时长为秒，小数，182.36
        _this.sectionData.videoSecond = Math.floor(duration)
      })
    },
    cancleFun () {
      this.visible = false
      this.showChapterManage = false
      this.showSectionManage = false
    },
    deleteChapter () {
      var _this = this
      this.$confirm('此操作将永久删除该章及章下的所有节, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.$delete(_this.chapterData, 'level')
        _this.$delete(_this.chapterData, 'children')
        _this.chapterData.remove = 0
        _this.$axios.post('/api/chapter/updateChapter',
          _this.$qs.stringify({
            chapterData: JSON.stringify(_this.chapterData)
          })
        ).then(res => {
          var data = res.data
          if (data.isSuccess) {
            var newChapter = data.result
            var yesIndex = -2
            for (var i = 0; i < _this.data.length; i++) {
              // eslint-disable-next-line eqeqeq
              if (_this.data[i].chapterId == newChapter.chapterId) {
                _this.data.splice(i, 1)
                yesIndex = i - 1
              }
              // eslint-disable-next-line eqeqeq
              if (yesIndex != -2 && i > yesIndex) {
                _this.data[i].sort -= 1
              }
            }
            _this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveChapter () {
      var _this = this
      var isSave = this.rightType
      this.$refs['chapter_info_form'].validate((valid) => {
        if (valid) {
          if (isSave) {
            _this.$delete(this.chapterData, 'level')
            _this.$delete(this.chapterData, 'children')
            this.$axios.post('/api/chapter/addChapter',
              this.$qs.stringify({
                chapterData: JSON.stringify(this.chapterData)
              })
            ).then(function (response) {
              if (response.data.isSuccess) {
                var newChapter = response.data.result
                newChapter.level = 1
                // eslint-disable-next-line no-array-constructor
                newChapter.children = new Array()
                _this.data.push(JSON.parse(JSON.stringify(newChapter)))
                _this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                _this.showChapterManage = false
              } else {
                _this.$message({
                  message: '保存失败，请重试！',
                  type: 'error'
                })
              }
            })
          } else {
            _this.$delete(this.chapterData, 'level')
            _this.$delete(this.chapterData, 'children')
            this.$axios.post('/api/chapter/updateChapter',
              this.$qs.stringify({
                chapterData: JSON.stringify(_this.chapterData)
              })
            )
              .then(function (response) {
                var result = response.data
                if (result.isSuccess) {
                  var newChapter = result.result
                  newChapter.level = 1
                  // eslint-disable-next-line no-array-constructor
                  newChapter.children = new Array()
                  for (var index in _this.data) {
                    const chapterId = _this.data[index].chapterId
                    // eslint-disable-next-line eqeqeq
                    if (chapterId == newChapter.chapterId) {
                      newChapter.children = _this.data[index].children
                      _this.data.splice(index, 1, newChapter)
                      // _this.setLeftChapter(_this.data[index], newChapter)
                      break
                    }
                  }
                  _this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  _this.showChapterManage = false
                } else {
                  _this.$message({
                    message: '保存失败，请重试',
                    type: 'error'
                  })
                }
              })
          }
        }
      })
    },
    deleteSection () {
      var _this = this
      this.$confirm('此操作将永久删除该节, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.$delete(_this.sectionData, 'level')
        _this.sectionData.remove = 0
        _this.$axios.post('/api/section/updateSection',
          _this.$qs.stringify({
            sectionData: JSON.stringify(_this.sectionData)
          })
        ).then(res => {
          var data = res.data
          if (data.isSuccess) {
            var newSection = data.result
            var yesIndex = -2
            var sections = _this.selectChapter.children
            for (var i = 0; i < sections.length; i++) {
              // eslint-disable-next-line eqeqeq
              if (sections[i].sectionId == newSection.sectionId) {
                sections.splice(i, 1)
                yesIndex = i - 1
              }
              // eslint-disable-next-line eqeqeq
              if (yesIndex != -2 && i > yesIndex) {
                sections[i].sort -= 1
              }
            }
            _this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveSection () {
      var _this = this
      var isSave = this.rightType
      this.$refs['section_info_form'].validate((valid) => {
        if (valid) {
          // isSave为true表示添加节
          // isSave为false表示 更新节
          if (isSave) {
            _this.$delete(_this.sectionData, 'level')
            _this.$axios.post('/api/section/addSection',
              _this.$qs.stringify({
                sectionData: JSON.stringify(_this.sectionData)
              })
            )
              .then(function (response) {
                var result = response.data
                if (result.isSuccess) {
                  var newSection = result.result
                  newSection.level = 2
                  _this.selectChapter.children.push(JSON.parse(JSON.stringify(newSection)))
                  _this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  _this.showSectionManage = false
                } else {
                  _this.$message({
                    message: '保存失败，请重试！',
                    type: 'error'
                  })
                }
              })
          } else {
            _this.$delete(_this.sectionData, 'level')
            _this.$axios.post('/api/section/updateSection',
              _this.$qs.stringify({
                sectionData: JSON.stringify(_this.sectionData)
              })
            )
              .then(function (response) {
                var result = response.data
                // 更新成功
                if (result.isSuccess) {
                  var newSection = result.result
                  newSection.level = 2
                  for (var index in _this.data) {
                    const chapterId = _this.data[index].chapterId
                    // eslint-disable-next-line eqeqeq
                    if (chapterId == newSection.chapterId) {
                      var data = _this.data[index].children
                      for (var i in data) {
                        const sectionId = data[i].sectionId
                        // eslint-disable-next-line eqeqeq
                        if (sectionId == newSection.sectionId) {
                          data.splice(i, 1, newSection)
                          break
                        }
                      }
                      break
                    }
                  }
                  _this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  _this.showSectionManage = false
                } else {
                  _this.$message({
                    message: '保存失败，请重试！',
                    type: 'error'
                  })
                }
              })
          }
        }
      })
    },
    async fileUploadCom (file) {
      var _this = this
      var host = this.$store.state.ossData.host
      var response = this.$Utils.getSignature('file')
      var requestData = new FormData()
      this.fileIng = true
      await response.then(res => {
        requestData = this.$Utils.fileUpload(file.file, res)
      })
      await this.$axios.post(host, requestData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: progressEvent => {
          let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
          _this.fileProgress = complete
          // file.onProgress({percent: complete})
        }
      })
        .then(function (response) {
          // eslint-disable-next-line eqeqeq
          if (response.status == 200) {
            _this.fileIng = false
            _this.sectionData.file = host + '/' + requestData.get('key')
            _this.sectionData.fileName = file.file.name
            _this.showFile = true
          }
        })
    },
    fileUploadChange (file, fileList) {
    },
    getCourseCS () {
      var _this = this
      this.$axios.post('api/course/getCourseCS',
        this.$qs.stringify({
          'courseId': _this.courseId
        }))
        .then(function (response) {
          var data = response.data
          if (data) {
            _this.data = JSON.parse(JSON.stringify(data.result))
          }
        })
    },
    getCourseById () {
      var _this = this
      this.$axios.post('api/course/gStCourseById',
        this.$qs.stringify({
          'courseId': _this.courseId
        }))
        .then(function (response) {
          var data = response.data
          if (data.isSuccess) {
            _this.course = JSON.parse(JSON.stringify(data.result))
          }
        })
    },
    goBack () {
      this.$router.push(this.$route.query.path)
    },
    setRightChapter (chapterData) {
      this.chapterData = JSON.parse(JSON.stringify(chapterData))
    },
    setLeftChapter (chapterData, data) {
      var children = chapterData.children
      chapterData = JSON.parse(JSON.stringify(data))
      chapterData.children = children
    },
    setRightSection (sectionData) {
      this.sectionData = JSON.parse(JSON.stringify(sectionData))
    }
  }
}
</script>

<style>
  .optionDiv {
    text-align: left;
  }

  .showText {
    text-align: left;
    font-size: 25px;
    font-weight: bolder;
  }

  .optionButton {
    display: inline-block;
    float: right;
  }

  .selectManageDiv {
    text-align: left;
    vertical-align: top;
  }

  .upload_div {
    display: inline-block;
  }

  .menu_top_div {
    height: 50px;
    line-height: 50px;
    background-color: #edeff1;
    color: #000000;
    font-size: 20px;
  }

  .tree_left {
    display: inline-block;
    text-align: left;
  }

  .tree_right {
    display: inline-block;
    text-align: center;
  }

  .el-tree-node__content {
    height: 50px;
  }

  .el-tree-node__expand-icon {
    font-size: 20px;
  }

  .custom-tree-node {
    display: inline-block;
    height: 40px;
    line-height: 40px;
    width: 100%;
    font-size: 20px
  }

  .addChapterBtn:hover {
    cursor: pointer;
    background-color: #b9bbbd;
  }
</style>
